package com.yaodian100.ec.order.web;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.csvreader.CsvWriter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.FileUtils;
import com.yaodian100.core.common.utils.JspUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.logger.service.CustomObjectStringConverter;
import com.yaodian100.core.logger.service.LogService;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.crm.workorder.service.WorkOrderService;
import com.yaodian100.ec.cobranding.entity.DPNStore;
import com.yaodian100.ec.cobranding.service.DPNService;
import com.yaodian100.ec.delivery.entity.ViewDeliveryRule;
import com.yaodian100.ec.delivery.service.DeliveryRuleService;
import com.yaodian100.ec.givebonus.service.BonusSettingService;
import com.yaodian100.ec.member.service.AddessService;
import com.yaodian100.ec.order.entity.OrderHistory;
import com.yaodian100.ec.order.entity.OrderMemo;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.OrderProductDetail;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.entity.ServiceOrders;
import com.yaodian100.ec.order.entity.Orders.ORDER_LOGISTIC_PROVIDER_TP;
import com.yaodian100.ec.order.service.OrderHistoryService;
import com.yaodian100.ec.order.service.OrderModifyService;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.order.service.ServiceOrderService;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.supplierapply.entity.SupplierApply;
import com.yaodian100.ec.supplierapply.service.SupplierApplyService;

/**
 * @author jinwei.lin
 * 
 */
public class OrderAction extends ActionSupport implements Preparable {

	private static final String RESULT_VIEW_ORDER_STATUS_HISTORY = "viewOrderStatusHistory";
	private static final long serialVersionUID = 178887580319281383L;
	/** logger */
	private final Logger logger = LoggerFactory.getLogger(OrderAction.class);

	@Autowired
	private LogService logService;
	@Autowired
	private ProductService productService;
	@Resource
	private ServiceOrderService serviceOrderService;

	@Resource(name = "supplierApplyService")
	private SupplierApplyService supplierApplyService;
	@Resource
	private OrderModifyService orderModifyService;
	private BigDecimal codFee = new BigDecimal(0);// COD﹣收取手續費
	@Resource
	private AddessService addressService;
	@Autowired
	private DPNService dpnService;

	private Menu orderStMenu; // 與 getter, setter
	private Menu paymentStMenu; // 與 getter, setter
	private Menu paymentTpMenu; // 與 getter, setter
	private Menu logisticStMenu; // 與 getter, setter
	private Menu returnStMenu; // 與 getter, setter
	private Menu detailTpMenu;
	private Menu logisticCompMenu;

	private String receiverName;
	private String pop;
	private String receiverMobile;
	private String receiverPhoneArea;
	private String receiverPhone;
	private String receiverExt;
	private String receiverZip;
	private String receiverAddr;
	private String province;
	private String receiverCity;
	private String receiverArea;
	private String invoiceTitle;
	private String actionResult;
	private String orderStCode;
	private String recvadddress;
	private String phone;
	private String recvadddressLike;
	private String phoneLike;

	private DomainService<Menu> menuService; // 與 setter
	private OrderService orderService;
	@Resource
	private OrderHistoryService orderHistoryService;
	private List<Orders> orders;
	private List<OrderProductDetail> orderProdDetail;
	private List<OrderHistory> orderHistoryList;
	private String orderId;
	private Orders order;
	private SimplePager pager;
	@Resource
	private BaseManager baseMgr;
	@Resource
	private JdbcTemplate jdbcTemplate;

	private SupplierApply supplierApply;

	private List<Orders> oldOrders;
	private String logTp;
	private String paytype;
	private String version;
	private String showCod;
	private String showPos;

	private List<OrderMemo> orderMemos;
	private OrderMemo orderMemo;

	// 查詢條件
	private String orderIdParam;
	private String orderDtStParam;
	private String orderDtEdParam;
	private String loginIdParam;
	private String orderStParam;
	private String paymentStParam;
	private String paymentTpParam;
	private String domainSrcParam;
	private String minDate;
	private String today;
	private String mobile;
	private Menu domainSrc;
	private String prodIdParam;
	private String receiverParam;
	private String outerOrderIdParam;
	private String tuangouIdParam;
	// private boolean hasSnapShot = false;
	private String snapShots;
	private List<ServiceOrders> cancelServiceOrders;
	private String newShipfare;
	private String storeId;
	private Map<String, String> provincesMap;
	@Autowired
	private DeliveryRuleService deliveryRuleService;
	@Autowired
	private BonusSettingService bonusSettingService;

	private InputStream ordserInputStream;
	@Resource
	private WorkOrderService workOrderService;

	private Map<String, String> prodVolumeMap;

	// 发票信息
	private String invotype;// 01－个人，02－单位
	private String invoTitle;

	public Menu getDomainSrc() {
		return domainSrc;
	}

	public void setDomainSrc(Menu domainSrc) {
		this.domainSrc = domainSrc;
	}

	public String getDomainSrcParam() {
		return domainSrcParam;
	}

	public void setDomainSrcParam(String domainSrcParam) {
		this.domainSrcParam = domainSrcParam;
	}

	/**
	 * @return the mobile
	 */
	public String getMobile() {
		return mobile;
	}

	/**
	 * @param mobile the mobile to set
	 */
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String returnProductInfo() {
		return "returnProductInfo";
	}

	public String changeProductInfo() {
		return "changeProductInfo";
	}

	/**
	 * 修改发票抬头
	 * 
	 * @return
	 * @throws Exception
	 */
	public String editInvoice() throws Exception {
		if (StringUtils.isNotBlank(orderId) || order.getOrderId() != null) {
			try {
				if (null != orderId) {
					order = orderService.get(orderId);
				} else {
					this.addActionError("订单编号未输入");
					return "search";
				}
			} catch (CoreException e) {
				addActionError(e.getMessage());
				e.printStackTrace();
			}
		}
		return "editInvoice";
	}

	/**
	 * 修改收件人资料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String editReceiver() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		if (StringUtils.isNotBlank(orderId)) {

			order = orderService.get(orderId);
			if (null != order) {
				// 地址簿-省
				provincesMap = deliveryRuleService.getOrderProvinces(orderId);
				if ("00".equals(order.getOrderSt()) || "10".equals(order.getOrderSt()) || "20".equals(order.getOrderSt())
						|| "05".equals(order.getOrderSt())) {
					if ("30".equals(order.getReceiverTp())) {
						if (StringUtils.isNotBlank(order.getStoreId())) {

							CommonCriteria crit = new CommonCriteria();
							crit.addEq("storeId", order.getStoreId());
							List<DPNStore> DPNStores = dpnService.getDPNStoretList(crit);
							if (DPNStores.size() > 0) {
								request.setAttribute("storeAreaInit", DPNStores.get(0).getStoreArea());
							}
						}
						return "editReceiverDph";
					} else {
						return "editReceiver";
					}
				} else {
					this.addActionError("此订单编号的订单状态已不允许修改收货人讯息。可修改的订单状态为订单审核中(货到付款)，等待付款(非货到付款)，或等待配货。");
					return view();
				}
			} else {
				this.addActionError("订单编号不存在");
				return "search";
			}

		} else {
			this.addActionError("订单编号未输入");
			return "search";
		}

	}

	/**
	 * 修改付款方式
	 * 
	 * @return
	 * @throws Exception
	 */
	public String editPaymentTp() throws Exception {
		showCod = "false";
		showPos = "N";
		if (StringUtils.isNotBlank(orderId)) {
			order = orderService.get(orderId);
			codFee = addressService.getCodFee();
			if (null != order) {
				if ("80".equals(order.getPaymentTp())) {
					this.addActionError("此订单编号所使用的支付方式不允许修改。");
					return view();
				} else {
					if ("00".equals(order.getOrderSt()) || "10".equals(order.getOrderSt())) {
						if (ORDER_LOGISTIC_PROVIDER_TP.NOT_COD_PROVIDER.getValue().equals(order.getLogisticProviderTp())) {
							showCod = "false";
							showPos = "N";
						} else {
							ViewDeliveryRule viewDeliveryRule = deliveryRuleService.canUseCodByOrderId(orderId);
							if ("Y".equals(viewDeliveryRule.getIsCod()) || "Y".equals(viewDeliveryRule.getIsPos())) {
								showCod = "true";
							}
							if ("Y".equals(viewDeliveryRule.getIsPos())) {
								showPos = "Y";
							}
							// 订单任一商品为scm不允许cod / pos
							if ("2".equals(order.getOrderType())) {
								showCod = "false";
								showPos = "N";
							}
						}
						return "editPaymentTp";
					} else {
						this.addActionError("此订单编号的订单状态已不允许修改支付方式。可修改的订单状态为订单审核中(货到付款)，或等待付款(非货到付款)。");
						return view();
					}
				}

			} else {
				this.addActionError("订单编号不存在");
				return "search";
			}
		} else {
			this.addActionError("订单编号未输入");
			return "search";
		}

	}

	public String getInvoiceTitle() {
		return invoiceTitle;
	}

	public String getLoginIdParam() {
		return loginIdParam;
	}

	public Menu getLogisticStMenu() {
		return logisticStMenu;
	}

	public String getMinDate() {
		return minDate;
	}

	public Orders getOrder() {
		return order;
	}

	public String getOrderDtEdParam() {
		return orderDtEdParam;
	}

	public String getOrderDtStParam() {
		return orderDtStParam;
	}

	public String getOrderId() {
		return orderId;
	}

	public String getOrderIdParam() {
		return orderIdParam;
	}

	public List<OrderProductDetail> getOrderProdDetail() {
		return orderProdDetail;
	}

	public List<Orders> getOrders() {
		return orders;
	}

	public Menu getOrderStMenu() {
		return orderStMenu;
	}

	public String getOrderStParam() {
		return orderStParam;
	}

	public SimplePager getPager() {
		return pager;
	}

	public Menu getPaymentStMenu() {
		return paymentStMenu;
	}

	public String getPaymentStParam() {
		return paymentStParam;
	}

	public Menu getPaymentTpMenu() {
		return paymentTpMenu;
	}

	public String getReceiverAddr() {
		return receiverAddr;
	}

	public String getReceiverCity() {
		return receiverCity;
	}

	public String getReceiverExt() {
		return receiverExt;
	}

	public String getReceiverMobile() {
		return receiverMobile;
	}

	public String getReceiverName() {
		return receiverName;
	}

	public String getReceiverPhone() {
		return receiverPhone;
	}

	public String getReceiverPhoneArea() {
		return receiverPhoneArea;
	}

	public String getReceiverZip() {
		return receiverZip;
	}

	public Menu getReturnStMenu() {
		return returnStMenu;
	}

	public String getToday() {
		return today;
	}

	/**
	 * 檢視订单資料(dialog, 沒套tiles)
	 * 
	 * @return
	 * @throws Exception
	 */
	public String popView() throws Exception {
		pop = "pop";
		view();
		return "popView";
	}

	public String fixInfo() {
		return "fixInfo";
	}

	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (org.apache.commons.lang.StringUtils.isBlank(orderDtStParam)) {
			orderDtStParam = DateUtil.convertDateToString("yyyy-MM-dd", DateUtil.getTodayAddDays(-7).getTime());
		}
		if (org.apache.commons.lang.StringUtils.isBlank(orderDtEdParam)) {
			orderDtEdParam = DateUtil.convertDateToString("yyyy-MM-dd", DateUtil.getToday().getTime());
		}
		if (StringUtils.isBlank(minDate)) {
			minDate = DateUtil.convertDateToString("yyyy,MM - 1,dd", DateUtil.getTodayAddDays(-60).getTime());
		}
		today = DateUtil.convertDateToString("yyyy,MM - 1,dd", DateUtil.getToday().getTime());
		if (orderStMenu == null) {
			orderStMenu = menuService.get("Order.status.md");
		}
		if (logisticStMenu == null) {
			logisticStMenu = menuService.get("Order.Prod.LogisticSt");
		}
		if (paymentStMenu == null) {
			paymentStMenu = menuService.get("Order.paymentSt");
		}
		if (paymentTpMenu == null) {
			paymentTpMenu = menuService.get("Order.PaymentTp");
		}
		if (returnStMenu == null) {
			returnStMenu = menuService.get("Order.Prod.ReturnSt");
		}
		if (detailTpMenu == null) {
			detailTpMenu = menuService.get("Product.Type");
		}
		if (null == domainSrc) {
			domainSrc = menuService.get("Site.domain");
		}

		if (null == logisticCompMenu) {
			logisticCompMenu = menuService.get("Logistic.company");
		}
	}

	private CommonCriteria queryOrderCtriteria() throws Exception {
		CommonCriteria crit = new CommonCriteria();

		if (StringUtils.isBlank(orderDtStParam)) {
			orderDtStParam = DateUtil.convertDateToString("yyyy-MM-dd", DateUtil.getTodayAddDays(-7).getTime());
		}
		if (StringUtils.isBlank(orderDtEdParam)) {
			orderDtEdParam = DateUtil.convertDateToString("yyyy-MM-dd", DateUtil.getToday().getTime());
		}

		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		crit.addGe("orderDt", format.parse(orderDtStParam + " 00:00:00"));
		crit.addLe("orderDt", format.parse(orderDtEdParam + " 23:59:59"));
		if (StringUtils.isNotBlank(mobile)) {
			crit.addEq("receiverMobile", mobile);
		}
		if (StringUtils.isNotBlank(orderIdParam)) {
			crit.addRlike("orderId", orderIdParam.trim());
		}
		if (StringUtils.isNotBlank(loginIdParam)) {
			crit.addRlike("loginId", loginIdParam.trim());
		}
		if (StringUtils.isNotBlank(orderStParam)) {
			crit.addEq("orderSt", orderStParam);
		}
		if (StringUtils.isNotBlank(paymentStParam)) {
			crit.addEq("paymentSt", paymentStParam);
		}
		if (StringUtils.isNotBlank(paymentTpParam)) {
			crit.addEq("paymentTp", paymentTpParam);
		}
		if (StringUtils.isNotBlank(outerOrderIdParam)) {
			crit.addEq("outerOrderId", outerOrderIdParam);
		}
		if (StringUtils.isNotBlank(domainSrcParam)) {
			crit.addEq("domainSrc", domainSrcParam);
		}

		if (StringUtils.isNotBlank(receiverParam)) {
			crit.addEq("receiverName", receiverParam);
		}
		if (StringUtils.isNotBlank(phone)) {
			if ("Y".equals(phoneLike)) {
				crit.addRlike("receiverPhone", phone + "%");
			} else {
				crit.addEq("receiverPhone", phone);
			}
		}
		if (StringUtils.isNotBlank(recvadddress)) {

			if ("Y".equals(recvadddressLike)) {
				crit.addRlike("receiverAddr", recvadddress + "%");
			} else {
				crit.addEq("receiverAddr", recvadddress);
			}
		}

		if (StringUtils.isNotBlank(prodIdParam)) {

			String sql = "select a.order_id from ec_order_main a, ec_order_product b where a.order_id = b.order_id and b.prod_id = ? and to_char(a.order_dt,'yyyymmdd') >= ? and to_char(a.order_dt,'yyyymmdd') <= ?";
			List<Map<String, Object>> orderList = jdbcTemplate.queryForList(sql, prodIdParam, StringUtils.replace(
					orderDtStParam, "-", ""), StringUtils.replace(orderDtEdParam, "-", ""));
			ArrayList<String> orderContainThisProd = new ArrayList<String>();
			for (Iterator<Map<String, Object>> orders = orderList.iterator(); orders.hasNext();) {
				Map<String, Object> order = orders.next();
				String orderId = (String) order.get("order_id");
				orderContainThisProd.add(orderId);

			}

			if (orderContainThisProd.size() > 0) {
				crit.addIn("orderId", orderContainThisProd);
			} else {
				orderContainThisProd.add("");
				crit.addIn("orderId", orderContainThisProd);
			}
		}
		if (StringUtils.isNotBlank(tuangouIdParam)) {
			crit.addEq("tuangouId", Long.parseLong(StringUtils.trim(tuangouIdParam)));
		}
		return crit;
	}

	/**
	 * 订单資料列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public String query() throws Exception {
		CommonCriteria crit = queryOrderCtriteria();

		if (pager == null) {
			pager = new SimplePager();
		}
		// pager.setPageRecord(1);
		int entitySize = orderService.getListSize(crit).intValue();
		pager.setTotalSize(entitySize);

		orders = orderService.getList(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(), crit,
				new String[] { "createDate desc" });
		// logger.info("pager:{},orders:{}", pager, orders);

		return "list";
	}

	public String exportOrderList() throws Exception {
		CommonCriteria crit = queryOrderCtriteria();
		orders = orderService.getList(0, -1, crit, new String[] { "orderId" });

		if (orders.size() > 0) {
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] BOM_UTF8 = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };// 加上bom檔頭，ms excel才能自行判斷
			output.write(BOM_UTF8);
			CsvWriter orderList = new CsvWriter(output, ',', Charset.forName("UTF-8"));
			orderList.writeRecord(new String[] { "订单编号", "商品编号", "商品名称", "收货人姓名", "收货人省", "收货人城市", "收货人地区", "收货人地址", "订购日期",
					"会员编号", "LOGIN_ID", "收货人行动电话", "购买数量", "订单状态", "订单总金额", "商品总金额", "礼券", "折扣", "购物金", "实付金额" });

			for (Orders order : orders) {
				for (OrderProduct op : order.getOrderProduct()) {
					String receiver = StringUtils.overlay(StringUtils.defaultString(order.getReceiverName()), "*", order
							.getReceiverName().length() - 1, order.getReceiverName().length());
					String receiveAddr = StringUtils.substring(StringUtils.defaultString(order.getReceiverAddr()), 0, 5) + "**";
					String receiveMobile = StringUtils.overlay(StringUtils.defaultString(order.getReceiverMobile()), "*****", 0,
							5);

					String orderDt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getOrderDt());
					String orderSt = menuService.get("Order.status").getOptions().get(order.getOrderSt()).getName();
					String orderQty = String.valueOf(op.getQty());

					orderList.writeRecord(new String[] { StringUtils.defaultString(order.getOrderId()),
							StringUtils.defaultString(op.getProdId()), StringUtils.defaultString(op.getProdName()), receiver,
							StringUtils.defaultString(order.getReceiverProvince()),
							StringUtils.defaultString(order.getReceiverCity()), StringUtils.defaultString(order.getReceiverArea()),
							receiveAddr, orderDt, StringUtils.defaultString(order.getMemberId()),
							StringUtils.defaultString(order.getLoginId()), receiveMobile, orderQty, orderSt,
							StringUtils.defaultString(order.getTotalPrice().toString()),
							StringUtils.defaultString(op.getTotalPrice().toString()),
							StringUtils.defaultString(order.getCoupon().toString()),
							StringUtils.defaultString(order.getDiscount().toString()),
							StringUtils.defaultString(order.getBonus().toString()),
							StringUtils.defaultString(order.getCash().toString()) });
				}
			}
			orderList.flush();
			orderList.close();
			ordserInputStream = new ByteArrayInputStream(output.toByteArray());
			output.flush();
			output.close();
			return "exportOrderList";
		} else {
			this.addActionError("无资料可汇出");
			return search();
		}

	}

	/**
	 * 查询
	 * 
	 * @return
	 * @throws Exception
	 */
	public String search() throws Exception {
		// setDomainSrcParam(ServerValue.getFrontHostname().substring(7));
		return "search";
	}

	public void setInvoiceTitle(String invoiceTitle) {
		this.invoiceTitle = invoiceTitle;
	}

	public void setLoginIdParam(String loginIdParam) {
		this.loginIdParam = loginIdParam;
	}

	public void setLogisticStMenu(Menu logisticStMenu) {
		this.logisticStMenu = logisticStMenu;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setMinDate(String minDate) {
		this.minDate = minDate;
	}

	public void setOrder(Orders order) {
		this.order = order;
	}

	public void setOrderDtEdParam(String orderDtEdParam) {
		this.orderDtEdParam = orderDtEdParam;
	}

	public void setOrderDtStParam(String orderDtStParam) {
		this.orderDtStParam = orderDtStParam;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public void setOrderIdParam(String orderIdParam) {
		this.orderIdParam = orderIdParam;
	}

	public void setOrderProdDetail(List<OrderProductDetail> orderProdDetail) {
		this.orderProdDetail = orderProdDetail;
	}

	public void setOrders(List<Orders> orders) {
		this.orders = orders;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public void setOrderStMenu(Menu orderStMenu) {
		this.orderStMenu = orderStMenu;
	}

	public void setOrderStParam(String orderStParam) {
		this.orderStParam = orderStParam;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public void setPaymentStMenu(Menu paymentStMenu) {
		this.paymentStMenu = paymentStMenu;
	}

	public void setPaymentStParam(String paymentStParam) {
		this.paymentStParam = paymentStParam;
	}

	public void setPaymentTpMenu(Menu paymentTpMenu) {
		this.paymentTpMenu = paymentTpMenu;
	}

	public void setReceiverAddr(String receiverAddr) {
		this.receiverAddr = receiverAddr;
	}

	public void setReceiverCity(String receiverCity) {
		this.receiverCity = receiverCity;
	}

	public void setReceiverExt(String receiverExt) {
		this.receiverExt = receiverExt;
	}

	public void setReceiverMobile(String receiverMobile) {
		this.receiverMobile = receiverMobile;
	}

	public void setReceiverName(String receiverName) {
		this.receiverName = receiverName;
	}

	public void setReceiverPhone(String receiverPhone) {
		this.receiverPhone = receiverPhone;
	}

	public void setReceiverPhoneArea(String receiverPhoneArea) {
		this.receiverPhoneArea = receiverPhoneArea;
	}

	public void setReceiverZip(String receiverZip) {
		this.receiverZip = receiverZip;
	}

	public void setReturnStMenu(Menu returnStMenu) {
		this.returnStMenu = returnStMenu;
	}

	public void setToday(String today) {
		this.today = today;
	}

	/**
	 * 更新发票抬头
	 * 
	 * @return
	 * @throws Exception
	 */
	public String updateInvoice() throws Exception {
		if (StringUtils.isNotBlank(orderId) || order.getOrderId() != null) {
			try {
				if (null != orderId) {
					order = orderService.get(orderId);
					order.setInvoiceTitle(invoiceTitle);
					orderService.updateOrder(order, "异常发票资料");
					logService.save("orderAction", "updateInvoice", order);
				} else {
					this.addActionError("订单编号未输入");
					return "editReceiver";
				}
			} catch (CoreException e) {
				addActionError(e.getMessage());
				e.printStackTrace();
			}
		}
		if ("pop".equals(pop)) {
			return popView();
		} else {
			return view();
		}
	}

	/**
	 * 更新收件人
	 * 
	 * @return
	 * @throws Exception
	 */
	public String updateReceiver() throws Exception {
		if (StringUtils.isNotBlank(orderId)) {
			try {
				Orders order = orderModifyService.get(orderId);
				if (null != order) {
					Map<String, Object> attrs = new HashMap<String, Object>();
					attrs.put("contactName", receiverName);
					attrs.put("areaCode", receiverPhoneArea);
					attrs.put("phone", receiverPhone);
					attrs.put("extension", receiverExt);
					attrs.put("mobile", mobile);

					boolean canChangeAddr = false;

					if ("30".equals(order.getPaymentTp()) || "60".equals(order.getPaymentTp())) {
						if ("00".equals(order.getOrderSt()) || ("20".equals(order.getOrderSt()) && !order.isSync())) {
							canChangeAddr = true;
						}
					} else if (!"www.yaodian100.com".equals(order.getDomainSrc())
							&& ("00".equals(order.getOrderSt()) || "05".equals(order.getOrderSt()))) {
						canChangeAddr = true;

					} else {
						if ("00".equals(order.getPaymentSt()) && "10".equals(order.getOrderSt())) {
							canChangeAddr = true;
						}
					}
					if (canChangeAddr) {
						attrs.put("province", province);
						attrs.put("city", receiverCity);

						attrs.put("addr", receiverAddr);
						attrs.put("midend", true);
						if ("30".equals(order.getReceiverTp())) {// 達芙妮
							attrs.put("district", receiverArea);
							attrs.put("storeId", storeId);
						} else {
							attrs.put("zipCode", receiverZip);
							receiverArea = receiverArea.split(",")[0];
							if (receiverArea.substring(0, 1).equals("※")) {
								receiverArea = receiverArea.substring(1);
							}
							attrs.put("district", receiverArea);
							attrs.put("version", version);

						}
						// 发票信息
						attrs.put("invotype", invotype);
						if ("02".equals(invotype)) {
							attrs.put("invoTitle", invoTitle);
						} else {
							attrs.put("invoTitle", "");
						}

					}
					orderModifyService.updateOrderAddres(orderId, attrs);
				} else {
					this.addActionError("订单编号不存在");
					return "search";
				}

			} catch (CoreException e) {
				if (orderModifyService.ERROR_ORDER_MODIFY_ADDRESS_Y1020N1020.equals(e.getLocalizedMessage())) {
					this.addActionError("商品发货处理中，无法修改订单");
				} else if (orderModifyService.ERROR_ORDER_MODIFY_ADDRESS_Y1020N1020_MIDEND.equals(e.getLocalizedMessage())) {
					this.addActionError("商品发货处理中，无法修改订单");
				} else if (orderModifyService.ERROR_ORDER_MODIFY_ADDRESS_Y3060N0020.equals(e.getLocalizedMessage())) {
					this.addActionError("商品发货处理中，无法修改订单");
				} else if (orderModifyService.ERROR_ORDER_MODIFY_ADDRESS_Y40N20.equals(e.getLocalizedMessage())) {
					this.addActionError("商品发货处理中，无法修改订单");
				} else if (orderModifyService.ERROR_ORDER_MODIFY_ADDRESS_Y50N1020.equals(e.getLocalizedMessage())) {
					this.addActionError("商品发货处理中，无法修改订单");
				} else {
					this.addActionError("订单修改遭遇无法遇期的错误");
				}
				e.printStackTrace();
			}
		} else {
			this.addActionError("订单编号未输入");
			return "search";
		}
		if ("pop".equals(pop)) {
			return popView();
		} else {
			return view();
		}
	}

	/**
	 * 更新付款方式
	 * 
	 * @return
	 * @throws Exception
	 */
	public String updatePaymentTp() throws Exception {
		if (StringUtils.isNotBlank(orderId)) {
			try {
				orderModifyService.updateOrderPaymentTp(orderId, paytype, true);
			} catch (CoreException e) {
				if (orderModifyService.ERROR_ORDER_MODIFY_PAYTYPE_Y3060N00.equals(e.getLocalizedMessage())) {
					this.addActionError("订单审核成功，无法修改订单");
				} else if (orderModifyService.ERROR_ORDER_MODIFY_PAYTYPE_Y50N10.equals(e.getLocalizedMessage())) {
					this.addActionError("订单已付款，无法修改订单");
				} else if (orderModifyService.ERROR_ORDER_MUSTPAY_BIGGER_VIRTUALBALANCE.equals(e.getLocalizedMessage())) {
					this.addActionError("帳戶余額不足，請改用其他支付方式");
				} else {
					this.addActionError("订单修改遭遇无法遇期的错误");
				}
				e.printStackTrace();
			}
		} else {
			this.addActionError("订单编号未输入");
			return "search";
		}
		if ("pop".equals(pop)) {
			return popView();
		} else {
			return view();
		}
	}

	public String updateShipfare() throws Exception {
		if (StringUtils.isNotBlank(orderId)) {
			try {
				orderModifyService.updateShipfare(orderId, newShipfare);
			} catch (CoreException e) {
				if (orderModifyService.ERROR_ORDER_MODIFY_SHIPFARE_NOO10.equals(e.getLocalizedMessage())) {
					this.addActionError("订单已付款，无法修改订单");
				} else if (orderModifyService.ERROR_ORDER_ORDER_NOT_EXISTS.equals(e.getLocalizedMessage())) {
					this.addActionError("订单编号不存在");
					return "search";
				} else {
					this.addActionError("订单修改遭遇无法遇期的错误");
				}
				e.printStackTrace();
			}
		} else {
			this.addActionError("订单编号未输入");
			return "search";
		}
		if ("pop".equals(pop)) {
			return popView();
		} else {
			return view();
		}
	}

	public String getPop() {
		return pop;
	}

	public void setPop(String pop) {
		this.pop = pop;
	}

	/**
	 * 檢視订单資料
	 * 
	 * @return
	 */
	public String view() throws Exception {
		if (StringUtils.isNotBlank(orderId)) {
			try {
				// order = orderService.get(orderId);
				// if (orderProdDetail != null) {
				// orderProdDetail = new ArrayList<OrderProductDetail>();
				// orderProdDetail.clear();
				// }else
				// orderProdDetail = new ArrayList<OrderProductDetail>();
				//				
				// for (OrderProduct op : order.getOrderProduct()) {
				// orderProdDetail.addAll(op.getOrderProductDetail());
				// }

				// logService.save(getClass().getSimpleName(), "view", theO);
				// order = (Orders) baseMgr.get(Orders.class, orderId);
				order = orderService.get(orderId);
				if (StringUtils.isNotBlank(order.getScmSupplierId())) {
					supplierApply = supplierApplyService.get(order.getScmSupplierId());
					setSupplierApply(supplierApply);
				} else {
					supplierApply = new SupplierApply();
					setSupplierApply(supplierApply);
				}

				IOFileFilter fileFilter = new PrefixFileFilter(orderId + "_");
				IOFileFilter dirFilter = null;

				String memberId = order.getMemberId();
				String snapShotFolder = ServerValue.getMidHtmlPath() + "member" + File.separatorChar + memberId.substring(0, 4)
						+ File.separatorChar + memberId.substring(4, 8) + File.separatorChar + memberId + File.separatorChar;
				if (new File(snapShotFolder).exists()) {
					Iterator c = FileUtils.iterateFiles(new File(snapShotFolder), fileFilter, dirFilter);
					String tempStr = "";
					while (c.hasNext()) {
						// hasSnapShot = true;
						File snapShot = (File) c.next();
						String productId = snapShot.getName().split("_")[1];
						tempStr += "," + productId;
					}
					if (tempStr.length() > 8) {
						snapShots = tempStr.substring(1);
					} else {
						snapShots = "";
					}
				}
				if (order.getOrderSt().startsWith("8")) {
					CommonCriteria cc = new CommonCriteria();
					cc.addEq("orderId", order.getOrderId());
					cc.addEq("srcType", 3);
					cancelServiceOrders = serviceOrderService.getList(0, -1, cc, new String[] { "serviceId" });

				} else {
					cancelServiceOrders = null;
				}
				prodVolumeMap = orderService.chkVolumeOfOrderDetail(order.getOrderId());
				logger.info("prodVolumeMap:{}", prodVolumeMap);
			} catch (CoreException e) {
				addActionError(e.getMessage());
				e.printStackTrace();
			}
		}
		return "view";
	}

	/**
	 * 更新狀態
	 * 
	 * @param orderId
	 * @return
	 * @throws CoreException
	 */
	public String updOrdSt() throws CoreException {
		logger.info("updOrdSt_orderId " + orderId);
		logger.info("updOrdSt_orderStCode " + orderStCode);

		if (true == orderService.updateOrderSt(orderId, orderStCode)) {
			// 检查工单
			String questionId = workOrderService.closeOrderForPayByProductArrive(orderId, JspUtil.username());
			if ("82".equals(orderStCode)) {
				Orders thisOrder = orderService.get(orderId);
				// 退還數量
				for (OrderProduct op : thisOrder.getOrderProduct()) {
					for (OrderProductDetail opd : op.getOrderProductDetail()) {
						CommonCriteria cc = new CommonCriteria();
						cc.addEq("specId", Long.parseLong(opd.getProdSpecId()));
						cc.addEq("productId", opd.getProdId());

						List<SpecificationInventory> si = productService.getSpecificationInventory(cc);
						for (SpecificationInventory entity : si) {
							entity.setCancelInventory(entity.getCancelInventory() + opd.getQty());
							productService.saveSpecificationInventory(entity);
						}
					}
				}
				// 退還已付款金額
				serviceOrderService.cancelOrderBySystem(orderId, "订单" + thisOrder.getOrderId() + " 审核失败，系统已取消该笔订单", "其它",
						thisOrder.getMemberId(), ServletActionContext.getRequest().getRemoteAddr(), thisOrder.getB2eId());
				// 寄信
				serviceOrderService.sendMail("order.cancelOrderOnVerify", "订单" + thisOrder.getOrderId() + " 审核失败，系统已取消该笔订单",
						thisOrder);
				orderService.updateOrderSt(orderId, orderStCode);
			}
			actionResult = "success";
			this.domainId = questionId;
		} else {
			actionResult = "update error!";
		}
		// return "update_st";
		if ("05".equals(orderStCode)) {
			try {
				return view();
			} catch (Exception e) {
				logger.warn(e.getMessage());
			}
			return "workOrderList";
		} else {

			return "workOrderList";
		}
	}

	private String domainId;

	/**
	 * @return the domainId
	 */
	public String getDomainId() {
		return domainId;
	}

	/**
	 * @param domainId the domainId to set
	 */
	public void setDomainId(String domainId) {
		this.domainId = domainId;
	}

	public String viewChangeLog() {
		try {
			oldOrders = new ArrayList<Orders>();
			order = orderService.get(orderId);
			String xml = "";
			String sql = "select log_message, create_date, create_user  from comm_log_order where order_id= ? and service_method = ? order by create_date desc";

			List<Map<String, Object>> data = jdbcTemplate.queryForList(sql, orderId, logTp);
			for (Iterator<Map<String, Object>> rows = data.iterator(); rows.hasNext();) {
				Map<String, Object> row = rows.next();
				xml = (String) row.get("log_message");
				Date createDt = (Date) row.get("create_date");
				String createUser = (String) row.get("create_user");

				StringReader xmlReader = new StringReader(xml);

				BeanReader beanReader = new BeanReader();
				beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
				beanReader.getXMLIntrospector().getConfiguration().setWrapCollectionsInElement(false);
				beanReader.getBindingConfiguration().setMapIDs(false);
				beanReader.getBindingConfiguration().setObjectStringConverter(new CustomObjectStringConverter());

				// Orders orders = (Orders)XMLUtils.(xmlReader, Orders.class);

				beanReader.registerBeanClass("Orders", Orders.class);
				Orders oldOrder = (Orders) beanReader.parse(xmlReader);
				oldOrder.setCreateDate(createDt); // 不使用原本order的，而是用log的
				oldOrder.setCreateUser(createUser);

				oldOrders.add(oldOrder);

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "viewChangeLog";
	}

	public String viewOrderStatusHistory() {
		String orderId = this.orderId;
		List<OrderHistory> orderHistoryQueryResult = this.orderHistoryService.getOrderHistory(orderId);
		setOrderHistoryList(orderHistoryQueryResult);
		return RESULT_VIEW_ORDER_STATUS_HISTORY;
	}

	public String toUpdateOrderAndShipfare() {
		try {
			view();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toUpdateOrderAndShipfare";
	}

	public String viewOrderMemo() {
		if (pager == null) {
			pager = new SimplePager();
		}
		if (StringUtils.isBlank(orderId)) {
			addActionError("订单编号不存在，重新选取");
		} else {
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("orderId", orderId);

			Number no = orderService.getOrderMemoSize(criteria);
			pager.setTotalSize(no.longValue());
			pager.setPageRecord(10);
			orderMemos = orderService.getOrderMemo(pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord(),
					criteria, null);
		}

		return "viewOrderMemo";
	}

	public String saveOrderMemo() {
		if (orderMemo == null) {
			addActionError("资料异动错误");
		}
		boolean isSave = true;
		try {
			orderMemo = orderService.saveOrderMemo(orderMemo);
			orderMemo = new OrderMemo();
		} catch (Exception e) {
			isSave = false;
		}
		if (isSave) {
			addActionMessage("储存成功");
		} else {
			addActionMessage("储存失败");
		}
		return viewOrderMemo();
	}

	public String getActionResult() {
		return actionResult;
	}

	public void setActionResult(String actionResult) {
		this.actionResult = actionResult;
	}

	public String getOrderStCode() {
		return orderStCode;
	}

	public void setOrderStCode(String orderStCode) {
		this.orderStCode = orderStCode;
	}

	public Menu getDetailTpMenu() {
		return detailTpMenu;
	}

	public void setDetailTpMenu(Menu detailTpMenu) {
		this.detailTpMenu = detailTpMenu;
	}

	public String getPaymentTpParam() {
		return paymentTpParam;
	}

	public void setPaymentTpParam(String paymentTpParam) {
		this.paymentTpParam = paymentTpParam;
	}

	public void setSupplierApplyService(SupplierApplyService supplierApplyService) {
		this.supplierApplyService = supplierApplyService;
	}

	public SupplierApply getSupplierApply() {
		return supplierApply;
	}

	public void setSupplierApply(SupplierApply supplierApply) {
		this.supplierApply = supplierApply;
	}

	public String getSnapShots() {
		return snapShots;
	}

	public void setSnapShots(String snapShots) {
		this.snapShots = snapShots;
	}

	public String getProdIdParam() {
		return prodIdParam;
	}

	public void setProdIdParam(String prodIdParam) {
		this.prodIdParam = prodIdParam;
	}

	public Menu getLogisticCompMenu() {
		return logisticCompMenu;
	}

	public void setLogisticCompMenu(Menu logisticCompMenu) {
		this.logisticCompMenu = logisticCompMenu;
	}

	public List<OrderHistory> getOrderHistoryList() {
		return this.orderHistoryList;
	}

	public void setOrderHistoryList(List<OrderHistory> orderHistoryList) {
		this.orderHistoryList = orderHistoryList;
	}

	public OrderHistoryService getOrderHistoryService() {
		return this.orderHistoryService;
	}

	public void setOrderHistoryService(OrderHistoryService orderHistoryService) {
		this.orderHistoryService = orderHistoryService;
	}

	public List<Orders> getOldOrders() {
		return oldOrders;
	}

	public void setOldOrders(List<Orders> oldOrders) {
		this.oldOrders = oldOrders;
	}

	public String getLogTp() {
		return logTp;
	}

	public void setLogTp(String logTp) {
		this.logTp = logTp;
	}

	public List<ServiceOrders> getCancelServiceOrders() {
		return cancelServiceOrders;
	}

	public void setCancelServiceOrders(List<ServiceOrders> cancelServiceOrders) {
		this.cancelServiceOrders = cancelServiceOrders;
	}

	public BigDecimal getCodFee() {
		return codFee;
	}

	public void setCodFee(BigDecimal codFee) {
		this.codFee = codFee;
	}

	public String getPaytype() {
		return paytype;
	}

	public void setPaytype(String paytype) {
		this.paytype = paytype;
	}

	public String getNewShipfare() {
		return newShipfare;
	}

	public void setNewShipfare(String newShipfare) {
		this.newShipfare = newShipfare;
	}

	public String getStoreId() {
		return storeId;
	}

	public void setStoreId(String storeId) {
		this.storeId = storeId;
	}

	public Map<String, String> getProvincesMap() {
		return provincesMap;
	}

	public void setProvincesMap(Map<String, String> provincesMap) {
		this.provincesMap = provincesMap;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getReceiverArea() {
		return receiverArea;
	}

	public void setReceiverArea(String receiverArea) {
		this.receiverArea = receiverArea;
	}

	public String getShowCod() {
		return showCod;
	}

	public void setShowCod(String showCod) {
		this.showCod = showCod;
	}

	public String getShowPos() {
		return showPos;
	}

	public void setShowPos(String showPos) {
		this.showPos = showPos;
	}

	/**
	 * @return the ordserInputStream
	 */
	public InputStream getOrdserInputStream() {
		return ordserInputStream;
	}

	/**
	 * @param ordserInputStream the ordserInputStream to set
	 */
	public void setOrdserInputStream(InputStream ordserInputStream) {
		this.ordserInputStream = ordserInputStream;
	}

	/**
	 * @return the receiverParam
	 */
	public String getReceiverParam() {
		return receiverParam;
	}

	/**
	 * @param receiverParam the receiverParam to set
	 */
	public void setReceiverParam(String receiverParam) {
		this.receiverParam = receiverParam;
	}

	public ServiceOrderService getServiceOrderService() {
		return this.serviceOrderService;
	}

	public void setServiceOrderService(ServiceOrderService serviceOrderService) {
		this.serviceOrderService = serviceOrderService;
	}

	/**
	 * @return the recvadddress
	 */
	public String getRecvadddress() {
		return recvadddress;
	}

	/**
	 * @param recvadddress the recvadddress to set
	 */
	public void setRecvadddress(String recvadddress) {
		this.recvadddress = recvadddress;
	}

	/**
	 * @return the phone
	 */
	public String getPhone() {
		return phone;
	}

	/**
	 * @param phone the phone to set
	 */
	public void setPhone(String phone) {
		this.phone = phone;
	}

	/**
	 * @return the recvadddressLike
	 */
	public String getRecvadddressLike() {
		return recvadddressLike;
	}

	/**
	 * @param recvadddressLike the recvadddressLike to set
	 */
	public void setRecvadddressLike(String recvadddressLike) {
		this.recvadddressLike = recvadddressLike;
	}

	/**
	 * @return the phoneLike
	 */
	public String getPhoneLike() {
		return phoneLike;
	}

	/**
	 * @param phoneLike the phoneLike to set
	 */
	public void setPhoneLike(String phoneLike) {
		this.phoneLike = phoneLike;
	}

	public Map<String, String> getProdVolumeMap() {
		return prodVolumeMap;
	}

	public void setProdVolumeMap(Map<String, String> prodVolumeMap) {
		this.prodVolumeMap = prodVolumeMap;
	}

	public String getInvotype() {
		return invotype;
	}

	public void setInvotype(String invotype) {
		this.invotype = invotype;
	}

	public String getInvoTitle() {
		return invoTitle;
	}

	public void setInvoTitle(String invoTitle) {
		this.invoTitle = invoTitle;
	}

	public List<OrderMemo> getOrderMemos() {
		return orderMemos;
	}

	public void setOrderMemos(List<OrderMemo> orderMemos) {
		this.orderMemos = orderMemos;
	}

	public OrderMemo getOrderMemo() {
		return orderMemo;
	}

	public void setOrderMemo(OrderMemo orderMemo) {
		this.orderMemo = orderMemo;
	}

	public String getOuterOrderIdParam() {
		return outerOrderIdParam;
	}

	public void setOuterOrderIdParam(String outerOrderIdParam) {
		this.outerOrderIdParam = outerOrderIdParam;
	}

	public String getTuangouIdParam() {
		return tuangouIdParam;
	}

	public void setTuangouIdParam(String tuangouIdParam) {
		this.tuangouIdParam = tuangouIdParam;
	}

}